import { pws } from '../network/api/index.js';
import { httpRequest } from '../network/index'
export default class CWebSocket {
  websock = null
  /**
   * @param voucherUrl 凭证接口
   * @param url 拼接的websocket接口
   * @param params 凭证接口的参数
   * @param callback websocket推送消息的回调
   */
  constructor(voucherUrl, url, params, callback) {
    this.voucherUrl = voucherUrl;
    this.url = pws.replace('https', 'wss').replace('http', 'ws') + url;
    this.params = params;
    this.callback = callback;
    this.initVoucher();
  }
  async initVoucher() {
    const { data } = await httpRequest(this.voucherUrl, this.params);
    this.initWebSocket(this.url + data);
  }
  initWebSocket = (url) => {
    this.websock = new WebSocket(url);
    this.websock.onopen = this.websocketonopen;
    this.websock.onerror = this.websocketonerror;
    this.websock.onmessage = this.websocketonmessage;
    this.websock.onclose = this.websocketclose;
  }
  websocketonopen = () => {
    console.log('组态连接状态，发送消息保持连接');
    if (this.websock?.readyState == 1) {
      this.websock.send('ping');
    }
    clearInterval(this.intervalId);
    this.intervalId = setInterval(() => {
      if (this.websock?.readyState == 1) {
        this.websock?.send('ping');
      }
    }, 300000);
  }
  websocketonerror = (e) => {
    console.log('组态websocket错误',e)
  }
  websocketonmessage = (e) => {
    if (e && e.data && e.data !== 'pong') {
      this.callback(e.data);
    }
  }
  websocketclose = (e) => {
    this.websock?.close();
    if (e && !this.isManualClose) {
      console.log('组态断开websocket~');
      clearTimeout(this.timeoutId);
      this.timeoutId = setTimeout(() => {
        this.initVoucher();
      }, 180000);
    }
    this.isManualClose = false
  }
  manualClose() {
    this.websock?.close();
    this.isManualClose = true
  }
}
